<template>
  <div class="digital-cockpit">
    <!-- 顶部导航 -->
    <van-nav-bar class="nav-bar">
      <template #title>
      <span class="nav-title">数字员工驾驶舱</span>
      </template>
    </van-nav-bar>
    <!-- 标签栏 -->
    <van-tabs v-model="activeTab" class="tab-bar" line-width="40px" line-height="3px" @click="handleTagClick">
      <van-tab title="个人工作台" class="tab-title" />
      <van-tab title="能力市场" class="tab-title" />
      <van-tab title="能力助手" class="tab-title" />
      <van-tab title="我的审批" class="tab-title" v-if="$store.getters.phone=='18908671899'" />
    </van-tabs>

    <!-- 搜索框 -->
    <div class="search-box" v-if="activeTab==0||activeTab==1">
      <van-search
          placeholder="搜索"
          v-model="keyword"
          background="#f5f5f5"
          shape="round"
          class="search-input"
          @search="init"
          @cancel="init"
      />
    </div>

    <!-- 个人工作台 -->
    <div class="digital-list" v-if="activeTab==0">
      <div class="digital-item" v-for="(item, index) in list" :key="index" @click="handleClick(item)">
        <!-- 数字人标题区域 -->
        <div class="digital-header">
          <div class="header-left">
            <van-image
                :src="getIcon(item.type)"
                alt="avatar"
                class="avatar"
                round
            />
            <div class="title-info">
              <h3 class="digital-title">{{ item.name }}</h3>

            </div>
          </div>
          <div v-if="item.reviewid!=null&&item.reviewstatus=='false'">
            <span class="switch-text" style="color: orange">公开能力审批中</span>
          </div>
          <div class="header-right" v-else>
            <span v-if="activeTab==0&&item.founder==$store.getters.userid">
            <span class="switch-text">是否公开</span>
              <van-switch v-model="item.ispublic" active-color="#07c160" size="24px" @change="openorclose(item)"/>
            </span>
          </div>
        </div>
        <van-divider class="h-divider" />
        <span><van-tag
                          plain
                          type="primary"
                          v-for="(profession, index) in item.professional"
                          :key="index"
                          style="margin-right: 4px;margin-bottom: 2px">
                        {{ profession }}
                      </van-tag>
                      </span>
        <p class="digital-desc">{{ item.description }}</p>

        <!-- 数字人信息卡片 -->
        <div class="info-card">
          <div class="info-row header-row">
            <div class="info-col">能力类型</div>
            <div class="info-col">订阅次数</div>
            <div class="info-col">来源</div>
            <div class="info-col">登记人</div>
          </div>
          <div class="info-row content-row">
            <div class="info-col" style="font-size: 15px">{{ showtype(item.type) }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.subscribecount }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.source }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.realname }}</div>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons">
          <span class="cancel-sub" v-if="item.founder!=$store.getters.userid" @click="cancelSubscription(item)">取消订阅</span>
          <span class="cancel-sub" v-else > </span>

          <div class="right-buttons">
            <span  v-if="activeTab==0&&item.type=='api'&&item.schedulingmode=='主动调度'">
              <span  v-if="item.xxlid!=null">
                <van-button
                  class="btn-executor"
                  v-if="item.xxlstatus=='0'"
                  size="small"
                  @click="start(item.xxlid)">
                  启动
                </van-button>
                <van-button
                    class="btn-pause"
                    v-else
                    size="small"
                    @click="stop(item.xxlid)">
                  暂停
                </van-button>
              </span>
              <van-button
                class="btn-executor"
                size="small"
                @click="openExecutor(item)">
                  执行器
                </van-button>
            </span>
            <van-button
              v-if="(activeTab==0&&item.type=='agent'&&item.founder==$store.getters.userid)||(activeTab==0&&item.type=='api')"
              class="btn-more"
              size="small"
              @click="handleMoreClick(item)"
          >
            更多
            <van-icon name="arrow-down" size="12" />
          </van-button>

          <!-- 动作面板（底部弹出） -->
          <van-action-sheet
              v-model="showActionSheet"
              :actions="moreActions"
              cancel-text="取消"
              @click-overlay="cancelActionSheet"
              @cancel="cancelActionSheet"
              @select="handleActionSelect"
          />
          </div>
        </div>
      </div>
    </div>

    <!-- 能力市场 -->
    <div class="digital-list" v-if="activeTab==1">
      <div class="digital-item" v-for="(item, index) in list" :key="index">
        <!-- 数字人标题区域 -->
        <div class="digital-header">
          <div class="header-left">
            <van-image
                :src="getIcon(item.type)"
                alt="avatar"
                class="avatar"
                round
            />
            <div class="title-info">
              <h3 class="digital-title">{{ item.name }}</h3>
            </div>
          </div>
        </div>
        <van-divider class="h-divider" />
        <span><van-tag
            plain
            type="primary"
            v-for="(profession, index) in item.professional"
            :key="index"
            style="margin-right: 4px;margin-bottom: 2px">
                        {{ profession }}
                      </van-tag>
                      </span>
        <p class="digital-desc">{{ item.description }}</p>

        <!-- 数字人信息卡片 -->
        <div class="info-card">
          <div class="info-row header-row">
            <div class="info-col">能力类型</div>
            <div class="info-col">订阅次数</div>
            <div class="info-col">来源</div>
            <div class="info-col">登记人</div>
          </div>
          <div class="info-row content-row">
            <div class="info-col" style="font-size: 15px">{{ showtype(item.type) }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.subscribecount }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.source }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.realname }}</div>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons">
          <span class="cancel-sub" />
          <div class="right-buttons">
            <span class="cancel-sub">
              <van-button
                  class="btn-executor"
                  size="small"
                  @click="SubscriptionDetails(item)"
                  v-if="$store.getters.phone=='18908671899'">订阅明细
              </van-button>
              <van-button
                  v-if="item.founder!=$store.getters.userid"
                  :class="item.mark!=null ?'btn-pause': 'btn-executor'"
                  size="small"
                  @click="handleButtonClick(item)">
                {{ buttonTextStatus(item.mark) }}
              </van-button>
          </span>
          </div>
        </div>
      </div>
      <van-pagination v-model="pageNo" :total-items="total" :items-per-page="pageSize" @change="init"/>
    </div>

    <!-- 能力助手 -->
    <div class="chat-container" v-if="activeTab==2">
      <div class="messages" ref="messagesContainer">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.role]"
        >
          <img
              v-if="message.role === 'assistant'"
              src="@/assets/logoz.png"
              alt="助手头像"
              class="avatar"
          >
<!--          <div class="message-bubble" v-html="message.content"></div>-->
          <div class="message-content" v-html="message.content">
            <div class="copy-btn" @click="copyCode($event)">
              <van-icon name="copy" size="16" color="#fff" />
            </div>
          </div>
        </div>
      </div>

      <!-- 记忆功能开关（Ant Design Vue组件） -->
      <div class="memory-switch">
        <span class="cancel-sub"></span>
        <span>记忆功能:</span>
        <van-switch
            v-model="memoryEnabled"
            @change="handleMemorySwitchChange"
            size="small"
        />
        <van-button size="small" class="btn-executor" @click="updateSubscriptionPanel">订阅管理</van-button>
      </div>
      <div class="input-footer">
        <form @submit.prevent="handleSubmit" class="input-form">
          <input
              type="text"
              v-model="input"
              :disabled="isLoading"
              placeholder="请输入问题..."
              class="input-box"
          >
          <button
              type="submit"
              :disabled="isLoading || !input.trim()"
              class="send-btn"
          >
            <img
                src="@/assets/fasong.png"
                alt="发送"
                class="send-icon"
                :class="{ 'send-icon-disabled': isLoading || !input.trim() }"
            >
          </button>
        </form>
      </div>
    </div>

    <!-- 我的订阅 -->
    <div class="digital-list" v-if="activeTab==3">

      <div class="digital-item" v-for="(item, index) in reviewlist" :key="index">
        <!-- 数字人标题区域 -->
        <div class="digital-header">
          <div class="header-left">
            <van-image
                :src="getIcon(item.type)"
                alt="avatar"
                class="avatar"
                round
            />
            <div class="title-info">
              <h3 class="digital-title">{{ item.name }}</h3>
            </div>
          </div>
        </div>
        <van-divider class="h-divider" />
        <span><van-tag
            plain
            type="primary"
            v-for="(profession, index) in item.professional"
            :key="index"
            style="margin-right: 4px;margin-bottom: 2px">
                        {{ profession }}
                      </van-tag>
                      </span>
        <p class="digital-desc">{{ item.description }}</p>

        <!-- 数字人信息卡片 -->
        <div class="info-card">
          <div class="info-row header-row">
            <div class="info-col">能力类型</div>
            <div class="info-col">来源</div>
            <div class="info-col">申请人</div>
            <div class="info-col">申请时间</div>
          </div>
          <div class="info-row content-row">
            <div class="info-col" style="font-size: 15px">{{ showtype(item.type) }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.source }}</div>
            <div class="info-col" style="font-size: 15px">{{ item.realname }}</div>
            <div class="info-col" style="font-size: 12px">{{ item.applytime }}</div>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons">
          <span class="cancel-sub" />
          <div class="right-buttons">

            <span class="cancel-sub">
              <van-button
                  class="btn-pause"
                  size="small"
                  @click="ThroughClick(item,false)">
                驳回
              </van-button>
               <van-button
                     class="btn-executor"
                     size="small"
                     @click="ThroughClick(item,true)">
                通过
              </van-button>
          </span>
          </div>
        </div>
      </div>
      <van-pagination v-model="pageNo" :total-items="total" :items-per-page="pageSize" @change="init"/>

    </div>
  </div>
</template>

<script>
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 代码高亮样式
import 'github-markdown-css/github-markdown.css'; // GitHub Markdown 基础样式
import { getAction,postAction } from '@/api'
import {Dialog} from "vant";
export default {
  components:{marked},
  data() {
    return {
      activeTab: 0,
      keyword: '',
      list: [],
      reviewlist: [],
      total:0,
      pageNo:1,
      pageSize:9,
      showMoreMenu:false,
      showActionSheet: false,
      moreActions: [],
      item:'',

      isSubscribed:false,

      messages: [
        {
          role: 'assistant',
          content: '我是数字分身，您的个人AI助手。请问有什么可以帮助您的？'
        }
      ],
      input: '',
      isLoading: false,
      memoryEnabled: false,
      conversationMap: {},
      psn_code:'',
    };
  },
  created() {
    marked.setOptions({
      highlight: (code, lang) => {
        // 代码高亮逻辑（仅执行一次初始化）
        if (lang && hljs.getLanguage(lang)) {
          return hljs.highlight(code, { language: lang }).value;
        }
        return hljs.highlightAuto(code).value;
      },
      gfm: true, // 支持表格、任务列表等 GitHub 语法
      breaks: true, // 支持换行符
      tables: true
    });
  },
  mounted() {
    if(this.$route.params.activeTab){
    this.activeTab=this.$route.params.activeTab
    }
    this.init()
    this.getPsnCode()

  },
  methods: {
    ThroughClick(item, value) {
      getAction('/sys/cockpitReview/Through',{id:item.id,marketId:item.marketId,value: value}).then(res => {
        if (res.code === 200) {
          this.$toast.success('操作成功');
          this.init();
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
    handleClick(item){
      event.stopImmediatePropagation()
      let params = item;
      params.activeTab=this.activeTab
      this.$router.push({name: 'Information', params: params})
    },
    getPsnCode(){
      getAction('/sys/getPsnCode',{username:this.$store.getters.username}).then(res=>{
        this.psn_code=res
      })
    },
    goBack() {
      //通讯录个人信息页面返回问题
      if(this.infoList.page){
        this.$router.push({name:this.infoList.page})
      }else{
        let parmas={
          title:this.$route.params.departName,
          orgCode:this.$route.params.orgCode
        }
        this.$router.push({name: 'member',params:parmas})
      }
    },
    handleTagClick(){
      this.init()
    },
    init(){
      if(this.activeTab==0){
        getAction('/sys/cockpitabilitymarket/list2', {keyword:this.keyword}).then(res=>{
          this.list = res.result.map(item => {
            // 将 professional 字段从字符串转换为数组
            return {
              ...item,
              professional: item.professional ? JSON.parse(item.professional) : []
            };
          });
        })
      }else if(this.activeTab==1){
        getAction('/sys/cockpitabilitymarket/list', {pageNo: this.pageNo, pageSize: this.pageSize,keyword:this.keyword,type:'',professional:''}).then(res=> {
          this.list = res.result.records.map(item => {
            // 将 professional 字段从字符串转换为数组
            return {
              ...item,
              professional: item.professional ? JSON.parse(item.professional) : []
            };
          });
          this.total = res.result.total;  // 总条数
        })
      }else if(this.activeTab==3){
        this.pageNo=1
        this.pageSize=9
        getAction('/sys/cockpitReview/approvallist', {pageNo: this.pageNo, pageSize: this.pageSize,activeTag:this.activeTag}).then(res=>{
          this.reviewlist = res.result.records.map(item => {
            // 将 professional 字段从字符串转换为数组
            return {
              ...item,
              professional: item.professional ? JSON.parse(item.professional) : []
            };
          });

          this.total = res.result.total;  // 总条数
        })
      }
    },
    buttonTextStatus(item) {
      return item !== null ? '取消订阅' : '订阅';
    },
    getIcon(type) {
      if (type === 'api') {
        return require('@/assets/api.png'); // API 对应图标
      } else if (type === 'agent') {
        return require('@/assets/zhinengti.png'); // Agent 对应图标
      }
      return require('@/assets/api.png'); // 默认图标
    },
    showtype(val){
      if(val=='agent'){
        return 'Agent'
      }else{
        return 'API接口'
      }
    },

    cancelSubscription(item) {
      event.stopImmediatePropagation()
      this.$dialog.confirm({
        title: '取消订阅',
        message: `确定要取消订阅 ${item.name} 吗？`,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
          .then(() => {
            const isSubscribed = item.mark !== null;
            item.isLoading = true;
            item.mark = isSubscribed ? null : 'subscribed';
            item.professional= JSON.stringify(item.professional)
            // 确认取消订阅
            postAction('/sys/cockpitabilitymarket/Subscribe', item) // 替换为你的实际API
                .then(res => {
                  if (res.code === 200) {
                    this.$toast.success(isSubscribed ? '取消订阅成功' : '订阅成功');
                    item.isLoading = false;
                    this.init()
                  } else {
                    this.$toast.fail(res.msg || '操作失败，请稍后重试');
                  }
                }).catch(err => {
                  console.log(err)
              item.isLoading = false;
            });
          })
          .catch(() => {
            // 用户点击了取消
            this.$toast('已取消操作');
          });
    },
    openorclose(item){
      event.stopImmediatePropagation()
      item.professional=JSON.stringify(item.professional)
      postAction('/sys/cockpitabilitymarket/openorclose',item).then(res=>{
        if(res.code == 200 && res.success) {
          this.$toast.success(res.result);
          this.init()
        } else {
          this.$toast.fail(res.message || '操作失败，请稍后重试');
          this.init()
        }
      })
    },
    start(id){
      event.stopImmediatePropagation()
      const jobId = parseInt(id);
      const loading = this.$toast.loading({
        message: '任务启动中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0 // 持续显示，直到手动清除
      });
      postAction('/sys/XxlJob/startJob', {id: jobId})
          .then(res => {
            if (res.message === '启动成功') {
              this.$toast.success(res.message);
            } else {
              this.$toast.fail(res.message || '任务启动失败');
            }
            this.init();
          })
          .catch(error => {
            this.$toast.fail('请求出错，请稍后重试');
            console.error('启动任务出错:', error);
          })
          .finally(() => {
            // 无论成功失败都清除加载提示
            loading.clear();
          });
      },
    stop(id) {
      event.stopImmediatePropagation()
      const jobId = parseInt(id);
      const loading = this.$toast.loading({
        message: '任务暂停中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0 // 持续显示，直到手动清除
      });

      postAction('/sys/XxlJob/stopJob', { id: jobId })
          .then(res => {
            if (res.message === '暂停成功') {
              this.$toast.success(res.message);
            } else {
              this.$toast.fail(res.message || '任务暂停失败');
            }
            this.init();
          })
          .catch(error => {
            this.$toast.fail('请求出错，请稍后重试');
            console.error('暂停任务出错:', error);
          })
          .finally(() => {
            // 无论成功失败都清除加载提示
            loading.clear();
          });
    },
    cancelActionSheet(){
      event.stopImmediatePropagation()
      this.showActionSheet = false;
    },
    handleActionSelect(action) {
      this.showActionSheet = false;
      if (action.key === 'detail') {
        Dialog.confirm({
          title: '确认执行',
          message: '确定要立即执行该任务吗？'
        }).then(() => {
          // 显示加载中提示
          const loading = this.$toast.loading({
            message: '任务执行中...',
            forbidClick: true,
            loadingType: 'spinner',
            duration: 0
          });

          postAction("/sys/cockpithaveability/Immediateexecution", {id: this.item.xxlid})
              .then(res => {
                if (res.code == 200) {
                  this.$toast.success(res.message || '执行成功');
                } else {
                  this.$toast.fail(res.message || '执行失败');
                }
              })
              .catch(error => {
                this.$toast.fail('请求出错，请稍后重试');
                console.error('任务执行出错:', error);
              })
              .finally(() => {
                loading.clear();
              });
        }).catch(() => {
          // 用户点击了取消
          this.$toast('已取消执行');
        });
      }

      if (action.key === 'delete') {
        Dialog.confirm({
          title: '提示',
          message: '若有用户订阅该能力也会同步删除，确定删除吗?？删除后无法恢复！'
        }).then(() => {
          // 显示加载中提示
          const loading = this.$toast.loading({
            message: '删除中...',
            forbidClick: true,
            loadingType: 'spinner',
            duration: 0 // 持续显示，直到手动清除
          });
          getAction('/sys/cockpitabilitymarket/delete', { id: this.item.id })
              .then(res => {
                if (res.code === 200) {
                  this.$toast.success('删除成功');
                  this.init();
                } else {
                  this.$toast.fail(res.msg || '删除失败');
                }
              })
              .catch(error => {
                this.$toast.fail('请求出错，请稍后重试');
                console.error('删除请求出错:', error);
              })
              .finally(() => {
                // 无论成功失败都清除加载提示
                loading.clear();
              });
        })
            .catch(() => {
              // 用户点击了取消
              this.$toast('已取消删除');
            });
      }
    },
    openExecutor(item) {
      event.stopImmediatePropagation()
      let params = item;
      params.activeTab=this.activeTab
      this.$router.push({name: 'actuator', params: params})
    },
    handleMoreClick(item) {
      event.stopImmediatePropagation()
      this.currentItem = item;
      this.showActionSheet = true;
      this.openActionSheet(item); // 准备动作菜单
    },
    openActionSheet(item) {
      this.item=item;
      this.moreActions = [];
      // 条件1：添加 "立即执行"
      if (this.activeTab == 0 && item.type == 'api' && item.schedulingmode == '主动调度' && item.xxlid != null) {
        this.moreActions.push({ name: '立即执行', key: 'detail' });
      }
      // 条件2：添加 "删除"（不与条件1冲突）
      if (this.activeTab == 0 && item.founder == this.$store.getters.userid && item.ispublic == false) {
        this.moreActions.push({ name: '删除', key: 'delete', color: '#f53f3f' });
      }
      // 如果没有符合任何条件，可以加一个默认选项
      if (this.moreActions.length === 0) {
        this.moreActions.push({ name: '无可用操作', key: 'none', disabled: true });
      }
      this.showActionSheet = true;
    },
    SubscriptionDetails(item) {
      let params = item;
      params.activeTab=this.activeTab
      this.$router.push({name: 'subscriptionDetails', params: params})
    },
    // 点击逻辑：切换订阅状态（模拟异步）
    handleButtonClick(item) {
      this.item=item;
      this.isSubscribed = item.mark !== null;
      if(this.isSubscribed==false) {
        if(item.type=='api'&&item.schedulingmode=='主动调度') {
          let params = item;
          params.activeTab=this.activeTab
          this.$router.push({name: 'actuator', params: params})
        }else {
          this.Subscribe(item);
        }
      }else{
        this.Subscribe(item);
      }
    },
    Subscribe(item){
      event.stopImmediatePropagation()
      item.isLoading = true;
      item.mark = this.isSubscribed ? null : 'subscribed'; // 切换订阅状态
      item.professional= JSON.stringify(item.professional)
      postAction('/sys/cockpitabilitymarket/Subscribe',item).then(res=>{
        if(res.code==200) {
          this.$toast.success(this.isSubscribed ? '取消订阅成功' : '订阅成功');
          item.isLoading = false; // 停止加载状态
          this.init(); // 重新加载数据
        }else {
          this.$toast.fail(res.msg || '操作失败，请稍后重试');
          item.isLoading = false; // 停止加载状态
          item.mark = this.isSubscribed ? 'subscribed' : null; // 恢复原状态
        }
      }).catch(() => {
        item.isLoading = false; // 停止加载状态
      })
    },
    //能力助手
    handleMemorySwitchChange(checked) {
      if (!checked) {
        // 关闭时清空所有记忆
        this.conversationMap = {};
        this.$toast('已清除所有对话记忆');
      }
    },
    async handleSubmit() {
      if (!this.input.trim() || this.isLoading) return;
      const userMessage = { role: 'user', content: this.input };
      this.messages.push(userMessage);
      const userInput = this.input;
      this.input = '';
      this.isLoading = true;
      try {
        const assistantMessage = {
          role: 'assistant',
          content: '',
          rawContent: ''
        };
        this.messages.push(assistantMessage);

        // 调用选择接口
        const param = {
          content: userInput,
          userid: this.$store.getters.userid
        };
        const res = await postAction('/chatapi/choice', param);
        if (res.code != 200) {
          this.$toast.fail(res.message);
          assistantMessage.content = '请求出错: ' + res.message;
        } else {
          var message = res.message.split('&&');
          if (message[0] != 'agent') {
            // 模拟流式输出返回的消息
            await this.simulateStreamingOutput(res.message, assistantMessage);
          } else {
            var api_id = message[1];
            // 如果是agent，显示提示信息
            assistantMessage.content = '正在连接智能体...';
            this.$toast('正在连接智能体...');
            // 直接在前端调用智能体接口
            await this.callAgentApiDirectly(userInput, api_id, assistantMessage);
          }
        }
      } catch (error) {
        console.error('Error:', error);
        this.messages[this.messages.length - 1].content = '抱歉，出错了: ' + error.message;
      } finally {
        this.isLoading = false;
        this.messages = [...this.messages];
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        container.scrollTop = container.scrollHeight;
      });
    },
    async callAgentApiDirectly(query, api_id, messageObj) {
      var info = `<userinfo>当前用户：${this.$store.getters.username}，当前用户姓名：${this.$store.getters.nickname}，当前用户手机号：${this.$store.getters.phone}，当前用户MSSID（工号）：${this.psn_code}</userinfo>`;

      try {
        // 构建请求体，根据记忆功能决定是否携带conversation_id
        const requestBody = {
          inputs: {},
          query: `${info}\n${query}`,
          response_mode: "streaming",
          conversation_id: this.memoryEnabled ? this.conversationMap[api_id] || "" : "",
          user: this.$store.getters.userid
        };

        const response = await fetch("/v1/chat-messages", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${api_id}`
          },
          body: JSON.stringify(requestBody)
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        let fullResponse = '';
        messageObj.content = '';

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });

          const lines = buffer.split(/\r\n|\r|\n/);
          buffer = lines.pop();

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const jsonStr = line.substring(6).trim();
              if (jsonStr === '') continue;

              try {
                const data = JSON.parse(jsonStr);

                // 存储conversation_id
                if (data.conversation_id && this.memoryEnabled) {
                  this.conversationMap[api_id] = data.conversation_id;
                }

                if ((data.event === 'agent_message' || data.event === 'message') && data.answer) {
                  const decodedAnswer = data.answer.replace(/\\u([\d\w]{4})/gi,
                      (match, grp) => String.fromCharCode(parseInt(grp, 16)));

                  fullResponse += decodedAnswer;
                  await this.streamOutput(fullResponse, messageObj);
                }
              } catch (e) {
                console.error('解析JSON出错:', e, '原始数据:', jsonStr);
              }
            }
          }
        }
      } catch (error) {
        console.error('调用智能体API出错:', error);
        messageObj.content = '调用智能体服务失败: ' + error.message;
        this.messages = [...this.messages];
        this.scrollToBottom();
        throw error;
      }
    },
    async streamOutput(fullText, messageObj) {
      // 计算需要新增的字符
      const currentLength = messageObj.rawContent ? messageObj.rawContent.length : 0;
      const newText = fullText.substring(currentLength);

      // 初始化rawContent如果不存在
      if (!messageObj.rawContent) {
        messageObj.rawContent = '';
      }
      // 逐字添加到原始内容
      for (let i = 0; i < newText.length; i++) {
        messageObj.rawContent += newText[i];

        // 解析为Markdown
        messageObj.content = marked.parse(this.convertToMarkdown(messageObj.rawContent));

        this.messages = [...this.messages];
        this.scrollToBottom();
        await new Promise(resolve => setTimeout(resolve, 30)); // 控制输出速度
      }
    },
    convertToMarkdown(input) {
      // 替换HTML实体
      let markdown = input
          .replace(/&gt;/g, '>')
          .replace(/&lt;/g, '<')
          .replace(/&quot;/g, '"')
          .replace(/<strong>name<\/strong>/g, '__name__')
          .replace(/<strong>main<\/strong>/g, '__main__');

      // 尝试识别代码块
      if (markdown.includes('def ') || markdown.includes('print(')) {
        // 确保代码块被正确包裹
        if (!markdown.startsWith('```python')) {
          markdown = "```python\n" + markdown.replace(/<\/?code>/g, '') + "\n```";
        }
      }

      // 移除残留的HTML标签
      markdown = markdown.replace(/<\/?p>/g, '');

      return markdown;
    },
// 模拟流式输出的方法（支持Markdown）
    async simulateStreamingOutput(text, messageObj) {
      // 初始化rawContent
      messageObj.rawContent = '';

      const characters = text.split('');
      for (let i = 0; i < characters.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 50));
        messageObj.rawContent += characters[i];

        // 解析为Markdown
        messageObj.content = marked.parse(this.convertToMarkdown(messageObj.rawContent));

        this.messages = [...this.messages];
        this.scrollToBottom();
      }
    },
    copyCode(event) {
      // 找到当前点击的复制图标所在的代码块（pre标签）
      const pre = event.target.closest('pre');
      if (!pre) return;
      // 找到代码块中的代码内容（code标签）
      const code = pre.querySelector('code');
      if (!code) return;
      // 使用浏览器API复制文本
      navigator.clipboard.writeText(code.textContent)
          .then(() => {
            this.$toast.success('复制成功'); // 提示复制成功（使用vant的toast组件）
          })
          .catch(err => {
            this.$toast.fail('复制失败'); // 提示复制失败
            console.error('复制失败:', err);
          });
    },
    updateSubscriptionPanel(){
      this.$router.push({name: 'subscription',params:{mark:'能力助手'}})
    },
  }
};
</script>

<style scoped>
.message-content {
  text-align: left;
  white-space: pre-line;
  white-space: pre-wrap;
}
/deep/ .van-tag--primary.van-tag--plain{
  background: #f2fffd;
  color: #26B1A1;
}
.nav-title {
  font-size: 16px;
  font-weight: bold;
  color: #26B1A1;
  letter-spacing: 0.5px;
}

.copy-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  opacity: 0.7; /* 初始半透明 */
  transition: opacity 0.3s; /*  hover 动画 */
}

.copy-btn:hover {
  opacity: 1; /* hover 时完全显示 */
}
/deep/ .van-overlay{
  background-color: rgb(0 0 0 / 15%) !important;
}
/deep/.van-switch{
  font-size: 16px !important;
}
.digital-cockpit {
  background-color: #f7f8fa;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 标签栏样式 */
.tab-bar {
  background-color: #fff;
  margin-bottom: 14px;
}

.tab-title {
  font-size: 16px;
  font-weight: 500;
}

/deep/.van-tabs__line {
  background-color: #27C2AD !important;
}
/deep/.van-tab--active{
  color: #27C2AD !important;
}

/* 搜索框样式 */
.search-box {
  padding: 0 16px 12px;
}

.search-input {
  background-color: white !important;
  border-radius: 5px;
  padding: 5px 0px !important;
}

.van-search__content{
  background-color: white !important;
}

/* 数字人列表样式 */
.digital-list {
  margin-bottom: 8vh;
  padding: 0 16px;
}

.digital-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 数字人标题区域 */
.digital-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.avatar {
  width: 26px;
  height: 26px;
  margin-right: 12px;
}

.title-info {
  min-width: 0;
}

/deep/.van-divider{
  margin: 0px 0px 6px 0px;
}

.digital-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.digital-desc {
  padding-bottom: 8px;
  font-size: 14px;
  color: #c0c4c8;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-right {
  display: flex;
  align-items: center;
}

.switch-text {
  position: relative;
  margin-left: 8px;
  font-size: 13px;
  color: #666;
  bottom: 2px;
  right: 8px;
}

/* 信息卡片样式 */
.info-card {
  width: 100%;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 6px;
}

.info-row {
  display: flex;
  width: 100%;
}

.header-row {
  background-color: #f4f8f9;
  color: #909399;
  font-size: 13px;
  border-bottom: 1px solid #e5e6eb;
}

.content-row {
  margin-top: -20px;
  background-color: #f5f7fa;
  color: #303133;
  font-size: 14px;
}

.info-col {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  position: relative;
}

.info-col:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 15%;
  height: 70%;
  width: 1px;
  background-color: #e5e6eb;
}
/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cancel-sub {
  color: #f53f3f;
  font-size: 14px;
  cursor: pointer;
  padding: 4px;
}

.right-buttons {
  display: flex;
  gap: 8px;
}

.btn-pause {
  background-color: #f53f3f;
  color: #fff;
  border-radius: 32px;
}

.btn-executor {
  background-color: #27C2AD !important;
  color: #fff;
  border-radius: 18px;
}

.btn-more {
  background-color: #e8f3ff;
  color: #1989fa;
  border-radius: 32px;
}

/* 适配小屏幕 */
@media (max-width: 375px) {
  .info-cell {
    flex: 0 0 50%;
  }

  .info-cell:nth-child(2)::after {
    display: none;
  }

  .info-cell:nth-child(3)::after {
    display: block;
  }
}


/* 能力助手 */


.chat-container {
  height: 84vh; /* 占满屏幕高度 */
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  overflow: hidden;
}

/* 消息列表：可滚动， flex占满剩余空间 */
.messages {
  flex: 1;
  padding: 20px 15px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;

/* 滚动条美化（仅WebKit内核） */
&::-webkit-scrollbar {
   width: 6px;
 }
&::-webkit-scrollbar-thumb {
   background-color: #ddd;
   border-radius: 3px;
 }
}

.message {
  display: flex;
  align-items: center;

}
.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}
.message-content {
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 100%;
  word-wrap: break-word;
  line-height: 1.8;
}
.message.user .message-content {
  max-width: calc(100% - 20px); /* 右边预留20px间距 */
  background-color: #e8f3ff;
  color: black;
  border-top-right-radius: 0;
  padding: 10px 15px;
  margin-left: auto; /* 右对齐 */
}
.message.assistant .message-content {
  max-width: calc(100% - 50px); /* 40px头像 + 10px间距 */
  background-color: #fff;
  color: #333;
  border-top-left-radius: 0;
  padding: 10px 15px; /* 增加内边距，让内容更清晰 */
}


/* 头像样式：圆形，固定大小 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover; /* 避免图片拉伸 */
}



/* 输入区域：固定底部，背景白色 */
.input-footer {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

/* 输入表单：flex布局，输入框自适应 */
.input-form {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}

/* 输入框：圆角、无边框、内边距 */
.input-box {
  flex: 1;
  padding: 12px 20px;
  border: 1px solid #eee;
  border-radius: 25px;
  outline: none;
  font-size: 14px;
  transition: border-color 0.3s;

&:focus {
   border-color: #07c160; /* 聚焦时边框变品牌色 */
 }

&:disabled {
   background-color: #f5f5f5;
   cursor: not-allowed;
 }
}

/* 发送按钮：无背景，图标垂直居中 */
.send-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
}

/* 发送图标：大小调整，禁用时灰化 */
.send-icon {
  width: 28px;
  height: 28px;
  vertical-align: middle;
  transition: opacity 0.3s;
}

.send-icon-disabled {
  opacity: 0.5; /* 禁用时图标半透明 */
  cursor: not-allowed;
}

/* 记忆功能开关：flex布局，对齐文字与开关 */
.memory-switch {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #666;
}


/* Markdown内容样式 */
.message-content {
  text-align: left;
}

.message-content >>> pre {
  white-space: pre-wrap; /* 关键：让代码自动换行 */
  background-color: #f6f8fa; /* 浅灰色背景，区分代码块 */
  border-radius: 5px;
  overflow-x: auto; /* 当代码过长时显示横向滚动条（可选） */
  font-size: 13px; /* 减小代码字体，节省空间 */
}

.message-content >>> code {
  font-family: 'Courier New', monospace;
  background-color: #e8f3ff; /* 浅蓝色背景，突出内联代码 */
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 13px;
}

.message-content >>> h1,
.message-content >>> h2,
.message-content >>> h3 {
  margin: 1em 0 0.5em;
  font-weight: bold;
}

.message-content blockquote {
  border-left: 4px solid #dfe2e5;
  /*color: #ffffff;*/
  padding: 0 1em;
  margin: 0 0 16px 0;
}

.message-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

.message-content th, .message-content td {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
}

.message-content tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.message-content tr:nth-child(2n) {
  background-color: #f6f8fa;
}
</style>
